//
//  GYBleCeshiViewController.m
//  LockManagement
//
//  Created by apple on 2018/8/23.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYBleCeshiViewController.h"
#import "GYBleDataManager.h"
#import "GYBleOperationManager.h"

@interface GYBleCeshiViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

/** <#description#> */
@property (nonatomic, strong) NSArray *lists;

/** <#description#> */
@property (nonatomic, strong) GYBleOperationManager *operationManager;

/** 收到的当前信息 */
@property (nonatomic, strong) NSData *currentData;

/** 记录协商出的秘钥 */
@property (nonatomic, strong) NSData *secret_key;

@end

@implementation GYBleCeshiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"蓝牙命令测试";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMessage:) name:BLEReceeiveMessage object:nil];
    
    self.operationManager.blueManagerStateChangedCallBack = ^(CBCentralManager *centerMnaager, CBManagerState state) {
        NSLog(@"===========%ld",(long)state);
    };
}

- (void)back {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)receiveMessage:(NSNotification *)noti {
    NSLog(@"receiveMessage===============%@",noti.object);
    //self.currentData = noti.object;
    
    //解析收到的数据
    NSData *messageData = noti.object;
    
    //1.首先判断是不是钥匙校时的消息
    NSData *headData = [messageData subdataWithRange:NSMakeRange(2, 1)];
    int length = [[GYBleDataManager convertDataToHexStr:headData] intValue];
    NSLog(@"length==================%d",length);
    if (length == 20) {
        NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];
        NSData *decryptData = [contentData LBXCryptWithOp:LBXOperaton_Decrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:@"TTMJ_234" iv:nil error:nil];
        NSLog(@"decryptData   20=========%@",decryptData);
    }else if (length == 21) {
        NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];
        NSData *decryptData = [contentData LBXCryptWithOp:LBXOperaton_Decrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:@"TTMJ_234" iv:nil error:nil];
        NSLog(@"decryptData   21=========%@",decryptData);
        //发送指令编号21
        NSData *data = [GYBleDataManager consultKeySecond:21 content:decryptData secret_key:@"TTMJ_234"];
        [self.operationManager sendMessage:data];
    }else if (length == 22) {
        NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];
        NSData *decryptData = [contentData LBXCryptWithOp:LBXOperaton_Decrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:@"TTMJ_234" iv:nil error:nil];
        NSLog(@"decryptData  22=========%@",decryptData);
        
        //发送指令编号是22
        NSData *data = [GYBleDataManager consultKeySecond:22 content:decryptData secret_key:decryptData];
        [self.operationManager sendMessage:data];
        self.currentData = decryptData;
    }else if (length == 23) {
        NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];
        NSData *decryptData = [contentData LBXCryptWithOp:LBXOperaton_Decrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:self.currentData iv:nil error:nil];
        self.secret_key = decryptData;
        NSLog(@"最后解析出来的秘钥 23=========%@",decryptData);
        
        //发送指令编号是23
//        NSData *data = [GYBleDataManager consultKeySecond:23 content:decryptData secret_key:decryptData];
//        [self.operationManager sendMessage:data];
    }else if (length == 5) {
        NSLog(@"表示收到钥匙授权返回的数据....");
        NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];
        NSData *decryptData = [contentData LBXCryptWithOp:LBXOperaton_Decrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:@"TTMJ_345" iv:nil error:nil];
        NSLog(@"decryptData==========%@",decryptData);
    }else if (length == 1) {
        NSLog(@"表示收到门锁信息.....");
        NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];
        NSData *decryptData = [contentData LBXCryptWithOp:LBXOperaton_Decrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:@"SDtt6789" iv:nil error:nil];
        NSLog(@"门锁信息==========%@",decryptData);
    }
}

#pragma mark -- UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.lists.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"cellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    cell.textLabel.text = self.lists[indexPath.row];
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"发送 -=====%@  =====消息",self.lists[indexPath.row]);
    switch (indexPath.row) {
        case 0:
        {
            //读取门锁信息(收发数据正常)
            NSData *data = [GYBleDataManager getLockInfomation];
            [self sendMessageData:data];
        }
            break;
            
        case 1:
        {
            //初始化门锁(收发数据正常)
            NSData *data = [GYBleDataManager setupLock];
            [self sendMessageData:data];
        }
            break;
            
        case 2:
        {
            //开门(1)
            if (self.secret_key) {
                NSLog(@"self.secret_key==========%@",self.secret_key);
                NSData *openDoorData = [GYBleDataManager openOrCloseTheDoor:@"1-2-7-1" schoolBeginTime:@"2016-09-01 10:10:10" schoolEndTime:@"2018-10-01 10:10:10" schoolTime:@"2016-09-01 10:10:10" operationType:1 SecretKey:self.secret_key];
                [self sendMessageData:openDoorData];
            }
        }
            break;
            
        case 3:
        {
            //关门(2)
        }
            break;
            
        case 4:
        {
            //锁设备日志上传
        }
            break;
            
        case 5:
        {
            //授权钥匙
            if (self.operationManager.connectType == deviceConntTypeSuccess) {
                //1.获取链接蓝牙的mac地址
                NSString *periphrealName = self.operationManager.periphreal.name;
                NSString *mac = [periphrealName substringWithRange:NSMakeRange(periphrealName.length-12, 12)];
                
                //Byte lock[] = {0x00,0x02,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
                Byte lock1[] = {0x8f,0x2e,0xab,0xab,0x55,0x36,0x1d,0xc3,0x38,0xfc,0xc5,0x8f,0xaa,0x9e,0x76,0x35};
                NSMutableData *lockData = [NSMutableData dataWithBytes:lock1 length:16];
                
                
                
                NSData *autoKeyData = [GYBleDataManager autoKey:lockData schoolBeginTime:@"2016-09-01 10:10:10" schoolEndTime:@"2099-09-01 10:10:10" schoolTime:@"2016-09-01 10:10:10" operationType:1 mac:mac];
                [self sendMessageData:autoKeyData];
            }
        }
            break;
            
        case 6:
        {
            //删除钥匙
        }
            break;
            
        case 7:
        {
            //读取蓝牙钥匙电量
            NSData *data = [GYBleDataManager getKeyElc];
            [self.operationManager sendMessage:data];
        }
            break;
            
        case 8:
        {
            //绑定蓝牙钥匙
            NSData *data = [GYBleDataManager bindBleKey];
            NSData *contentData;
            int count = data.length/20 + 1;
            
            Byte *testByte =(Byte *)[data bytes];
            
        
            
            for (int i = 0; i < count; i++) {
                Byte ceshi[20] = {0};
                for (int k=0; k < 20; k++) {
                    ceshi[k] = testByte[i*20+k];
                }
                NSData *ceshiData = [NSData dataWithBytes:ceshi length:20];
                [self.operationManager sendMessage:ceshiData];
                [NSThread sleepForTimeInterval:0.01];
//                if ((data.length - contentData.length) > 20) {
//
//                    contentData = [data subdataWithRange:NSMakeRange(20*i, 20)];
//                    NSLog(@"sendMessageData =======%@",contentData);
//                    [self.operationManager sendMessage:contentData];
//                    [NSThread sleepForTimeInterval:0.01];
//                }else {
//                    contentData = [data subdataWithRange:NSMakeRange(20*i, data.length-20*i)];
//                    NSMutableData *removeData = [NSMutableData dataWithLength:20];
//                    [removeData replaceBytesInRange:NSMakeRange(0, contentData.length) withBytes:contentData.bytes];
//                    NSLog(@"sendMessageData =======%@",removeData);
//                    [self.operationManager sendMessage:data];
//                }
            }
            //[self.operationManager sendMessage:data];
        }
            break;
            
        case 9:
        {
            //查询锁具详情信息(可以收到返回)
            NSData *data = [GYBleDataManager getLockDetailesInfomations];
            [self.operationManager sendMessage:data];
        }
            break;
            
        case 10:
        {
            //给锁校时 这个加密的秘钥需要 协商通讯秘钥---> 产生秘钥之后才可以
            NSData *data = [GYBleDataManager schoolTimeToLock];
            [self.operationManager sendMessage:data];
        }
            break;
            
        case 11:
        {
            //重置秘钥 ---> 命令加密的秘钥 ---> 通讯秘钥 ----->  通讯秘钥使用旧的初始化秘钥协商生成
            NSData *data = [GYBleDataManager resetSecretKey];
            [self.operationManager sendMessage:data];
        }
            break;
            
        case 12:
        {
            //修改锁识别号 ->  可能传入锁的识别号
            NSData *data = [GYBleDataManager modfyLockNumber];
            [self.operationManager sendMessage:data];
        }
            break;
            
        case 13:
        {
            //给钥匙校时
            if (self.operationManager.connectType == deviceConntTypeSuccess) {
                NSData *data = [GYBleDataManager schoolTimeToKey];
                
                NSData *contentData;
                int count = data.length/20 + 1;
                
                Byte *testByte =(Byte *)[data bytes];
                
                
                
                for (int i = 0; i < count; i++) {
                    Byte ceshi[20] = {0};
                    for (int k=0; k < 20; k++) {
                        ceshi[k] = testByte[i*20+k];
                    }
                    NSData *ceshiData = [NSData dataWithBytes:ceshi length:20];
                    [self.operationManager sendMessage:ceshiData];
                    [NSThread sleepForTimeInterval:0.01];
                    
                }
                //[self.operationManager sendMessage:data];
            }else {
                [SVProgressHUD showInfoWithStatus:@"蓝牙未连接"];
            }
        }
            break;
            
        case 14:
        {
            //通讯秘钥(协商)(可以收到返回 测试通过)
            NSData *data = [GYBleDataManager consultKey];
            [self.operationManager sendMessage:data];
        }
            
        default:
            break;
    }
}

#pragma 蓝牙的发送数据 处理方法 --- 这个蓝牙收发最多只能20字节,超过20字节的需要自己分段  分成20字节一段开始发送

/**
 针对蓝牙发送的数据做一个分包处理
 
 @param messageData <#messageData description#>
 */
- (void)sendMessageData:(NSData *)messageData {
    if (messageData.length > 20) {
        NSData *contentData;
        int count = messageData.length/20 + 1;
        
        Byte *testByte =(Byte *)[messageData bytes];
        for (int i = 0; i < count; i++) {
            Byte ceshi[20] = {0};
            for (int k=0; k < 20; k++) {
                ceshi[k] = testByte[i*20+k];
            }
            NSData *ceshiData = [NSData dataWithBytes:ceshi length:20];
            [self.operationManager sendMessage:ceshiData];
            [NSThread sleepForTimeInterval:0.01];
        }
    }else {
        [self.operationManager sendMessage:messageData];
    }
}

#pragma mark -- 懒加载

- (NSArray *)lists {
    if (!_lists) {
        _lists = @[@"获取门锁信息",@"初始化门锁",@"开门",@"关门",@"锁设备日志上传",@"授权钥匙",@"删除钥匙",@"读取蓝牙钥匙电量",@"绑定蓝牙钥匙",@"查询锁详细信息",@"给锁校时",@"重置秘钥",@"修改锁识别号",@"钥匙校时",@"通讯秘钥(协商秘钥)"];
    }
    
    return _lists;
}

- (GYBleOperationManager *)operationManager {
    if (!_operationManager) {
        _operationManager = [GYBleOperationManager shareOperationManager];
    }
    
    return _operationManager;
}

@end
